//
//  PostListViewController.m
//  XPhoto
//
//  Created by sentinel on 2020/3/20.
//  Copyright © 2020 baboy. All rights reserved.
//

#import "PostBaseViewController.h"
#import "SerialPostDetailViewController.h"
#import "PostAction.h"
#import "UIViewController+share.h"
#import "Comment.h"
#import "PostDetailViewController.h"
#import "TopicPostViewController.h"
#import "TagPostViewController.h"
#import "UserProfileViewController.h"
#import "UIScrollView+x.h"
#import <UShareUI/UShareUI.h>
#import "BKWebViewController.h"
#import "SysDict.h"
#import <BKKit/NSString+x.h>

#define ACTION_SHEET_TAG_FAV        100
#define ACTION_SHEET_TAG_SHARE      101
#define ACTION_SHEET_TAG_COMPLAINT  102

@interface PostBaseViewController ()

@end

@implementation PostBaseViewController

- (BKCommentView *)commentView{
    if (!_commentView) {
        _commentView = [BKCommentView view];
    }
    _commentView.delegate = self.actionDelegate;
    return _commentView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.actionDelegate = self;
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    //    DLOG(@"originContentInset:%@,contentOffset:%@", NSStringFromUIEdgeInsets(self.tableView.originContentInset), NSStringFromCGPoint(self.tableView.contentOffset));
    //    self.tableView.originContentInset = UIEdgeInsetsMake(self.tableView.contentOffset.y, 0, 0, 0);
}
#pragma mark - BKTableView Delegate
- (PhotoTableViewCell *)photoTableViewCellForTableView:(UITableView*)tableView{
    PhotoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: PHOTO_TABLE_VIEW_CELL_REUSE_ID];
    if (!cell) {
        cell = loadViewFromNib([PhotoTableViewCell class], self);
    }
    cell.delegate = self.actionDelegate;
    return cell;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSInteger n = self.posts.count;
    return n;
}
//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//    return UITableViewAutomaticDimension;
//    PhotoTableViewCell *cachedCell = [self photoTableViewCellForTableView:tableView];
//    Post *post = [self.posts objectAtIndex:indexPath.row];
//    CGFloat h = [cachedCell cellHeightWithPost:post width:tableView.bounds.size.width];
//    return h;
//}
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 490;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    PhotoTableViewCell *cell = [self photoTableViewCellForTableView:tableView];
    Post *post = [self.posts objectAtIndex:indexPath.row];
    cell.post = post;
    cell.userAvatarButton.userInfo = post.user;
    return cell;
}

#pragma mark - PhotoTableViewCellDelegate
- (void)photoTableViewCellDidClickUserAvatarButton:(id)photoTableViewCell{
    
    Post *post = [photoTableViewCell post];
    UserProfileViewController *vc = [[UserProfileViewController alloc] init];
    vc.user = post.user;
    [self.navigationController pushViewController:vc animated:YES];
    
}
- (void)photoTableViewCellDidClickLikeButton:(id)photoTableViewCell{
    Post *post = [photoTableViewCell post];
    PostAction *action = [PostAction new];
    action.postId = post.id;
    
    [BKIndicator showMessage:NSLocalizedString(@"add_like_now", @"提示")];
    [PostAction addLike:action
               callback:^(id  _Nonnull task, id  _Nullable json, NSError * _Nullable error) {
        if (error) {
            [BKIndicator showMessageAndFadeOut:error.localizedDescription completion:nil];
            return;
        }
        [BKIndicator showMessageAndFadeOut:NSLocalizedString(@"add_success", @"提示") completion:nil];
    }];
    
}
- (void)addFavoriteWithPost:(Post *)post{
    PostAction *action = [PostAction new];
    action.postId = post.id;
    
    [BKIndicator showMessage:NSLocalizedString(@"add_favorite_now", @"提示")];
    [PostAction addFav:action
              callback:^(id  _Nonnull task, id  _Nullable json, NSError * _Nullable error) {
        if (error) {
            [BKIndicator showMessageAndFadeOut:error.localizedDescription completion:nil];
            return;
        }
        [BKIndicator showMessageAndFadeOut:NSLocalizedString(@"add_success", @"提示") completion:nil];
    }];
}
- (void)photoTableViewCellDidClickFavButton:(id)photoTableViewCell{
    Post *post = [photoTableViewCell post];
    [self addFavoriteWithPost:post];
    
}

- (void)photoTableViewCellDidClickShareButton:(id)photoTableViewCell{
    Post *post = [photoTableViewCell post];
    [self shareWithPost:post];
}
- (void)photoTableViewCellDidClickCommentButton:(id)photoTableViewCell{
    Post *post = [photoTableViewCell post];
    PostDetailViewController *vc = [[PostDetailViewController alloc] init];
    vc.post = post;
    [self.navigationController pushViewController:vc animated:YES];
    
}

- (void)photoTableViewCellDidClickAddCommentButton:(id)photoTableViewCell{
    Post *post = [photoTableViewCell post];
    self.commentView.tag = post.id;
    [self.commentView show];
}
- (void)photoTableViewCellDidClickMenuButton:(id)photoTableViewCell{
    Post *post = [photoTableViewCell post];
    NSArray *options = @[
        @{
            @"title":NSLocalizedString(@"favorite", @"按钮"),
            @"tag":@(ACTION_SHEET_TAG_FAV),
            @"data":post
        },
        @{
            @"title":NSLocalizedString(@"share", @"按钮"),
            @"tag":@(ACTION_SHEET_TAG_SHARE),
            @"data":post
        },
        @{
            @"title":NSLocalizedString(@"complaint", @"按钮"),
            @"tag":@(ACTION_SHEET_TAG_COMPLAINT),
            @"data":post
        }
    ];
    BKActionSheet *actionSheet = [[BKActionSheet alloc] initWithItems:options
                                                             delegate:self
                                                    cancelButtonTitle:NSLocalizedString(@"cancel", @"按钮")];
    [actionSheet show];
}
- (void)photoTableViewCell:(id)photoTableViewCell openLink:(NSURL *)url{
    if ([[url scheme] isEqualToString:APP_LINK_SCHEME]) {
        //点击喜欢人数标签
        if( [[url host] isEqualToString:APP_LINK_TYPE_LIKE] ){
        }
        //点击评论数标签
        if( [[url host] isEqualToString:APP_LINK_TYPE_COMMENT] ){
            [self photoTableViewCellDidClickCommentButton:photoTableViewCell];
        }
        //点击话题
        if( [[url host] isEqualToString:APP_LINK_TYPE_TOPIC] ){
            TopicPostViewController *vc = [[TopicPostViewController alloc] init];
            vc.topic = [url lastPathComponent];
            [self.navigationController pushViewController:vc animated:YES];
            
        }
        //点击@对象
        if( [[url host] isEqualToString:APP_LINK_TYPE_USER] ){
            UserProfileViewController *vc = [[UserProfileViewController alloc] init];
            vc.uid = [photoTableViewCell post].uid;
            [self.navigationController pushViewController:vc animated:YES];
            
            
        }
    }
}

- (void)photoTableViewCell:(id)photoTableViewCell didSelectSerial:(PostSerial *)postSerial ofPost:(Post *)post{
    SerialPostDetailViewController *vc = [[SerialPostDetailViewController alloc] init];
    vc.postSerial = postSerial;
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)photoTableViewCell:(id)photoTableViewCell didSelectLocationOfPost:(Post *)post{
    
}
- (void)photoTableViewCell:(id)photoTableViewCell didSelectTag:(NSString *)tag ofPost:(Post *)post{
    TagPostViewController *vc = [[TagPostViewController alloc] init];
    vc.tag = tag;
    vc.post = post;
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark - BKCommentViewDelegate
- (void)commentView:(BKCommentView*)view didClickedSendButton:(id)button{
    NSString *content = [view.textView.text?:@"" stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    if (!content || content.length == 0) {
        [BKIndicator showMessageAndFadeOut:NSLocalizedString(@"content_should_not_be_null", @"提示") completion:nil];
        return;
    }
    Comment *comment = [Comment new];
    comment.content = content;
    comment.postId = view.tag;
    [BKIndicator showMessage:NSLocalizedString(@"submitting", @"提交数据")];
    [Comment add:comment
        callback:^(id  _Nonnull task, id  _Nullable json, NSError * _Nullable error) {
        if (error) {
            [BKIndicator showMessageAndFadeOut:error.localizedDescription completion:nil];
            return;
        }
        view.textView.text = nil;
        [BKIndicator showMessageAndFadeOut:NSLocalizedString(@"submit_success", @"提交数据") completion:nil];
    }];
}
#pragma mark - BKActionSheetDelegate
- (void)actionSheet:(BKActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex data:(id)data{
    NSInteger tag = [[data valueForKey:@"tag"] intValue];
    Post *post = [data valueForKey:@"data"];
    if (tag == ACTION_SHEET_TAG_FAV) {
        [self addFavoriteWithPost:post];
    }
    if (tag == ACTION_SHEET_TAG_SHARE) {
        [self shareWithPost:post];
    }
    if (tag == ACTION_SHEET_TAG_COMPLAINT) {
        SysDictItem *dictItem = [SysDict itemForKey:SYS_DICT_ITEM_KEY_COMPLAINT_LINK dictKey:SYS_DICT_KEY_WEB_LINK];
        NSString *complaintUrl = dictItem.value;
        NSDictionary *param = @{
            @"postId":@(post.id)
        };
        complaintUrl = [complaintUrl URLStringWithParam:param];
        
        BKWebViewController *vc = [[BKWebViewController alloc] init];
        vc.currentURL = [NSURL URLWithString:complaintUrl];
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
        nav.modalPresentationStyle = UIModalPresentationFullScreen;
        [self presentViewController:nav animated:YES completion:nil];
    }
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
